﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.IO;
using System.Web.Caching;

namespace KPIS.GERP.GIMS.APP.APP_UI.UserControl
{
    public partial class ICM_Receive_Item : System.Web.UI.UserControl
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        IBLLResourceMasterItem bll = new ResourceMasterItemBLL();
        RecevieItemBLL recitemBLL = new RecevieItemBLL();
        DeliveryNoteItemBLL dnitemBLL = new DeliveryNoteItemBLL();
        HrmJobSiteBLL jsBLL = new HrmJobSiteBLL();

        //public static ResourceMasterItemInfo itemInfo = new ResourceMasterItemInfo();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadUnit();
            }
        }
        public void SetHeader(string header)
        {
            lblHeaderList.Text = "รายการพัสดุภายใต้ <" + header + ">";
        }
        public void LoadDataGrid()
        {
            IList<ReceiveItemInfo> info = recitemBLL.GetReceiveItems((int?)null, Convert.ToInt32(Session["RECEIVESEQ"]), "");
            Grid.DataSource = info;
            Grid.DataBind();

            cmdFac.GridCommand(panelList, panelGrid, panelCommand);
        }

        private void LoadUnit()
        {
            IBLLMasterUnit unit = new MasterUnitBLL();
            IList<MasterUnitInfo> info = unit.GetMasterUnit();
            cmbUnit.DataSource = info;
            cmbUnit.DataBind();
        }

        public void GetKeyValue(string seq)
        {
            if (seq.Length > 0)
            {
                ReceiveItemInfo itemInfo = new ReceiveItemInfo();
                IList<ReceiveItemInfo> info = recitemBLL.GetReceiveItems(Int32.Parse(seq), (int?)null, "");

                if (info.Count > 0)
                {
                    itemInfo = info[0];

                    cmbDnItem.SelectedValue = itemInfo.DeliveryNoteItem.Seq.ToString();
                    cmbToJobSite.SelectedValue = itemInfo.JobSiteSeq.Seq.ToString();
                    txtSerialNumber.Text = itemInfo.SerialNumber;
                    txtDescr.Text = itemInfo.Description;
                    txtAccessary.Text = itemInfo.Accessary;
                    txtQty.Text = itemInfo.Quantity.ToString();
                    txtPrice.Text = itemInfo.UnitPrice.ToString();
                    txtDateExpired.Text = itemInfo.DateExpired.ToString();
                    txtRemark.Text = itemInfo.Remark;
                    //cmbUnit.SelectedValue = itemInfo.InfoUnit.Seq.ToString();
                    //if (cmbUnit.SelectedValue == "")
                    //{
                    //    cmbUnit.SelectedIndex = -1;
                    //    cmbUnit.Text = "";
                    //}
                    
                    //imgPhoto.Dispose();
                    //imgPhoto.ImageUrl = (itemInfo.Image_name.Length > 0
                    //    ? SystemInfo._ImagePath + itemInfo.Image_name + "?n=" + DateTime.Now.ToString()
                    //    : SystemInfo._EmptyImage + "?n=" + DateTime.Now.ToString());

                    cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
                    PanelPhoto.Visible = false;
                    ((HiddenField)this.Parent.FindControl("hdChangeFile")).Value = "";
                }
            }
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
            PanelPhoto.Visible = true;
            imgPhoto.ImageUrl = SystemInfo._EmptyImage;
            ((HiddenField)this.Parent.FindControl("hdChangeFile")).Value = "";
        }

        protected void Edit_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList, panelGrid, panelCommand);
            PanelPhoto.Visible = true;
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            IList<ReceiveItemInfo> infoList = new List<ReceiveItemInfo>();
            if (panelGrid.Visible)
            {
                foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
                {
                    ReceiveItemInfo info = new ReceiveItemInfo();
                    info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                    info.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());

                    infoList.Add(info);
                }
            }
            else
            {
                ReceiveItemInfo info = new ReceiveItemInfo();

                info.Seq = Convert.ToInt32(((HiddenField)this.Parent.FindControl("hdSeq")).Value);
                info.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());

                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                ((RadAjaxManager)this.Parent.FindControl("RadManager1")).Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                recitemBLL.DeleteAll(infoList);
                ((Form.ICM_ReceiveItem)this.Parent.Parent.Parent.Parent.Parent.Parent.Parent).RefreshTree();
            }
            catch
            {
                ((RadAjaxManager)this.Parent.FindControl("RadManager1")).Alert(SystemInfo._DeleteError);
                return;
            }

            LoadDataGrid();
        }

        protected void AddNewSave_Click(object sender, EventArgs e)
        {
            ReceiveItemInfo info = new ReceiveItemInfo();
            M_IcmReceiveObject rcInfo = new M_IcmReceiveObject();
            ResourceMasterItemInfo resInfo = new ResourceMasterItemInfo();
            MasterUnitInfo infoUnit = new MasterUnitInfo();
            ImageInfo infoImage = new ImageInfo();
            DeliveryNoteItemInfo dnitemInfo = new DeliveryNoteItemInfo();
            RecordInfo infoRecord = new RecordInfo();
            HrmJobSiteInfo jsInfo = new HrmJobSiteInfo();
            string source_file = ((HiddenField)this.Parent.FindControl("hdSourceFile")).Value;
            if (source_file.Length > 0)
            {
                FileInfo fiSource = new FileInfo(source_file);
                infoImage.File_info = fiSource;
            }
            int ReceiveSeq = Convert.ToInt32(Session["RECEIVESEQ"]);
            rcInfo.icm_receive_seq = ReceiveSeq;
            info.ReceiveSeq = rcInfo;
            dnitemInfo.Seq = cn.ConvertNullInt(cmbDnItem.SelectedValue);
            info.DeliveryNoteItem = dnitemInfo;
            resInfo.Seq = null; // cn.ConvertNullInt(drc[i]["icm_res_item_seq"]);
            info.ResourceItemSeq = resInfo;
            jsInfo.Seq = cn.ConvertNullInt(cmbToJobSite.SelectedValue);
            info.JobSiteSeq = jsInfo;
            info.LotNumber = "";
            info.SerialNumber = txtSerialNumber.Text;
            info.UpperItemSeq = cn.ConvertNullInt(Session["ParentID"].ToString());
            info.DateExpired = cn.ConvertNullDateTime(txtDateExpired.TextWithLiterals);
            info.Description = txtDescr.Text.Trim();
            info.Accessary = txtAccessary.Text.Trim();
            info.Quantity = Int32.Parse(txtQty.Text);
            info.UnitPrice = Convert.ToDouble(txtPrice.Text);
            info.Remark = txtRemark.Text.Trim();
            info.Created_by = Int32.Parse(Session["EmpSeq"].ToString());

            try
            {
                recitemBLL.Insert(info);
                ((Form.ICM_Master_Resource)this.Parent.Parent.Parent.Parent.Parent.Parent.Parent).RefreshTree();
            }
            catch
            {
                ((RadAjaxManager)this.Parent.FindControl("RadManager1")).Alert(SystemInfo._InsertError);
                return;
            }

            LoadDataGrid();
        }

        protected void EditSave_Click(object sender, EventArgs e)
        {           
            ReceiveItemInfo info = new ReceiveItemInfo();
            M_IcmReceiveObject rcInfo = new M_IcmReceiveObject();
            ResourceMasterItemInfo resInfo = new ResourceMasterItemInfo();
            MasterUnitInfo infoUnit = new MasterUnitInfo();
            ImageInfo infoImage = new ImageInfo();
            DeliveryNoteItemInfo dnitemInfo = new DeliveryNoteItemInfo();
            RecordInfo infoRecord = new RecordInfo();
            HrmJobSiteInfo jsInfo = new HrmJobSiteInfo();
            string source_file = ((HiddenField)this.Parent.FindControl("hdSourceFile")).Value;
            if (source_file.Length > 0)
            {
                FileInfo fiSource = new FileInfo(source_file);
                infoImage.File_info = fiSource;
            }

            info.Seq = Convert.ToInt32(((HiddenField)this.Parent.FindControl("hdSeq")).Value);
            dnitemInfo.Seq = cn.ConvertNullInt(cmbDnItem.SelectedValue);
            info.DeliveryNoteItem = dnitemInfo;
            resInfo.Seq = null; // cn.ConvertNullInt(drc[i]["icm_res_item_seq"]);
            info.ResourceItemSeq = resInfo;
            jsInfo.Seq = cn.ConvertNullInt(cmbToJobSite.SelectedValue);
            info.JobSiteSeq = jsInfo;
            info.LotNumber = "";
            info.SerialNumber = txtSerialNumber.Text;
            info.UpperItemSeq = cn.ConvertNullInt(Session["ParentID"].ToString());
            info.DateExpired = cn.ConvertNullDateTime(txtDateExpired.TextWithLiterals);
            info.Description = txtDescr.Text.Trim();
            info.Accessary = txtAccessary.Text.Trim();
            info.Quantity = Int32.Parse(txtQty.Text);
            info.UnitPrice = Convert.ToDouble(txtPrice.Text);
            info.Remark = txtRemark.Text.Trim();
            info.Created_by = Int32.Parse(Session["EmpSeq"].ToString());

            try
            {
                recitemBLL.Update(info);
                ((Form.ICM_Master_Resource)this.Parent.Parent.Parent.Parent.Parent.Parent.Parent).RefreshTree();
            }
            catch
            {
                ((RadAjaxManager)this.Parent.FindControl("RadManager1")).Alert(SystemInfo._InsertError);
                return;
            }
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
            PanelPhoto.Visible = false;
            //if (info.Image_name.Length > 0)
            //{
            //    imgPhoto.ImageUrl = (info.Image_name.Length > 0
            //            ? SystemInfo._ImagePath + info.Image_name + "?n=" + DateTime.Now.ToString()
            //            : SystemInfo._EmptyImage + "?n=" + DateTime.Now.ToString());
            //}
            //else
            //{
            //    imgPhoto.ImageUrl = (itemInfo.Image_name.Length > 0
            //            ? SystemInfo._ImagePath + itemInfo.Image_name + "?n=" + DateTime.Now.ToString()
            //            : SystemInfo._EmptyImage + "?n=" + DateTime.Now.ToString());
            //}
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList, panelGrid, panelCommand);
            PanelPhoto.Visible = false;
        }

        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            LoadDataGrid();
        }

        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadDataGrid();
        }

        protected void clearFilter_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid.MasterTableView.FilterExpression = string.Empty;
            LoadDataGrid();
        }
        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }
        protected void cmbDnItem_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<DeliveryNoteItemInfo> infoList = dnitemBLL.GetDeliveryNoteItemWithParent(1);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbDnItem.Items.Add(new RadComboBoxItem(infoList[i].Descr, infoList[i].Seq.ToString()));

                TableRow tr = new TableRow();

                TableCell tdCode = new TableCell();
                Label lblCode = new Label();
                lblCode.Text = infoList[i].Seq.ToString();
                tdCode.Width = Unit.Pixel(150);
                tdCode.Controls.Add(lblCode);
                tr.Cells.Add(tdCode);

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Descr;
                tdName.Width = Unit.Pixel(250);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);

                ((Table)cmbDnItem.Items[j].FindControl("tableDnItem")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }
        protected void cmbToJobSite_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            // By KHIM *********************************************
            IList<HrmJobSiteInfo> infoList = jsBLL.GetJobSite(e.Text);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbToJobSite.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));

                TableRow tr = new TableRow();

                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(250);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                ((Table)cmbToJobSite.Items[j].FindControl("tableToJobSite")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }
    }
}